<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\model\Options;
use think\Request;
use think\Response;

class Option extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return Response
     */
    public function index()
    {
        //
        $this->checkLogin(true);
        $page = $this->request->param('page', 1);
        $data = Options::page($page, 50)->select();
        return $this->success('sucess', $data);
    }

    /**
     * 保存新建的资源
     *
     * @param Request $request
     * @return Response
     */
    public function save(Request $request)
    {
        //
        $this->checkLogin(true);
        $data = $request->post(['name', 'value', 'group']);
        $option = Options::where('name', $data['name'])->find();
        if (!empty($option)) return $this->error('配置已存在');
        $option = Options::create($data);
        return $this->success('success', $option);
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return Response
     */
    public function read($id)
    {
        //
        $this->checkLogin(true);
        $option = Options::find($id);
        if (empty($option)) return $this->error('配置不存在');
        return $this->success('success', $option);
    }

    /**
     * 保存更新的资源
     *
     * @param Request $request
     * @param int $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        //
        $this->checkLogin(true);
        $data = $request->post(['name', 'value', 'group']);
        $option = Options::find($id);
        if (empty($option)) return $this->error('配置不存在');
        $option->save($data);
        return $this->success('success', $option);
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id)
    {
        //
        $this->checkLogin(true);
        Options::destroy($id);
        return $this->success('delete success');
    }
}
